<template>
  <div class="app-container home">
    <div class="station-top">
      <el-row :gutter="12" class="mt5">
        <!-- <el-col :span="4">
          <div class="top-item-box item-box-one" style="display: flex">
            <div style="flex: 2; height: 100%">
              <div>
                <div>流量称一号机（高温）</div>
                <div style="margin-top: 5px; color: #fff;">{{ topLL.time1 }}</div>
              </div>
              <div style="text-align: center; margin-top: 30px">
                <span style="font-size: 26px; font-weight: bold">{{ topLL.weight1 }}（KG）</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="top-item-box item-box-one" style="display: flex">
            <div style="flex: 2; height: 100%">
              <div>
                <div>流量称二号机（高温）</div>
                <div style="margin-top: 5px; color: #fff;">{{ topLL.time2 }}</div>
              </div>
              <div style="text-align: center; margin-top: 30px">
                <span style="font-size: 26px; font-weight: bold">{{ topLL.weight2 }}（KG）</span>
              </div>
            </div>
          </div>
        </el-col> -->
        <!-- <el-col :span="5">
          <div class="top-item-box item-box-two" style="display: flex">
            <div style="flex: 2; height: 100%">
              <div>
                <div>流量称三号机（破碎）</div>
                <div style="margin-top: 5px; color: #fff;">{{ topLL.time3 }}</div>
              </div>
              <div style="text-align: center; margin-top: 30px">
                <span style="font-size: 26px; font-weight: bold">{{ topLL.weight3 }}（KG）</span>
              </div>
            </div>
          </div>
        </el-col> -->
        <el-col :span="8">
          <div class="top-item-box item-box-one" style="display: flex">
            <div style="flex: 1; height: 100%; flex-shrink: 0;">
              <div style="font-size: 22px;">原料数量（吨）</div>
              <div style="text-align: center; margin-top: 30px">
                <span style="font-size: 26px; font-weight: bold">{{ (staObj.stockIn - topLL.weight1).toFixed(2) }}</span>
              </div>
            </div>
            <div
              style="
                display: flex;
                flex-direction: column;
                justify-content: space-evenly;
              "
            >
              <div>入库数量：
                <div>{{ staObj.stockIn }}</div>
              </div>
              <div>加工数量：
                <div>{{ topLL.weight1 }}</div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="top-item-box item-box-two" style="display: flex">
            <div style="flex: 1; height: 100%; flex-shrink: 0;">
              <div style="font-size: 22px;">加工结存（吨）</div>
              <div style="text-align: center; margin-top: 30px">
                <span style="font-size: 22px; font-weight: bold">{{ (topLL.weight1 - staObj.stockOut).toFixed(2)  }}</span>
              </div>
            </div>
            <div
              style="
                display: flex;
                flex-direction: column;
                justify-content: space-evenly;
              "
            >
              <div>加工数量：
                <div>{{ topLL.weight1 }}</div>
              </div>
              <div>出库数量：
                <div>{{ staObj.stockOut }}</div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="top-item-box item-box-two" style="display: flex">
            <div style="flex: 2; height: 100%">
              <div>
                <div style="font-size: 22px;">加工数量（吨）</div>
              </div>
              <div style="text-align: center; margin-top: 30px">
                <span style="font-size: 26px; font-weight: bold">{{ topLL.weight1 }}</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="top-item-box item-box-three" style="display: flex">
            <div style="flex: 2; height: 100%">
              <div style="font-size: 22px;">入库（吨）</div>
              <div style="text-align: center; margin-top: 30px">
                <span style="font-size: 26px; font-weight: bold">{{
                  statisticIn.today
                }}</span>
              </div>
            </div>
            <div
              style="
                flex: 3;
                display: flex;
                flex-direction: column;
                justify-content: space-evenly;
              "
            >
              <div>昨日：{{ statisticIn.yesterday }}</div>
              <div>近7天：{{ statisticIn.recent }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="top-item-box item-box-four" style="display: flex">
            <div style="flex: 2; height: 100%">
              <div style="font-size: 22px;">出库（吨）</div>
              <div style="text-align: center; margin-top: 30px">
                <span style="font-size: 26px; font-weight: bold">{{
                  statisticOut.today
                }}</span>
              </div>
            </div>
            <div
              style="
                flex: 3;
                display: flex;
                flex-direction: column;
                justify-content: space-evenly;
              "
            >
              <div>昨日：{{ statisticOut.yesterday }}</div>
              <div>近7天：{{ statisticOut.recent }}</div>
            </div>
          </div>
        </el-col>
        <!-- <el-col :span="6">
          <div class="top-item-box item-box-three" style="display: flex;">
            <div style="flex:2;height:100%;">
              <div>其他</div>
              <div style="text-align:center;margin-top:30px;"><span style="font-size:26px;font-weight:bold;"
              >15</span></div>
            </div>
            <div style="flex:3;display: flex;flex-direction:column;justify-content:space-evenly">
              <div>待截单：5</div>
              <div>异常单：5</div>
              <div>今日到货：5</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="top-item-box item-box-four" style="display: flex;">
            <div style="flex:2;height:100%;">
              <div>库存预警</div>
              <div style="text-align:center;margin-top:30px;"><span style="font-size:26px;font-weight:bold;">5</span>
              </div>
            </div>
            <div style="flex:3;display: flex;flex-direction:column;justify-content:space-evenly">
              <div>松陵仓：1</div>
              <div>盛泽仓：2</div>
              <div>园区仓：2</div>
            </div>
          </div>
        </el-col> -->
      </el-row>
    </div>
    <div class="station-middle">
      <el-row :gutter="12">
        <!-- <el-col :span="6">
          <el-card class="box-card" shadow="never">
            <div class="card-title">仓库货物占比</div>
            <div style="height: calc(100% - 30px);">
              <StationPie height="100%"></StationPie>
              <div></div>
            </div>
          </el-card>
        </el-col> -->
        <el-col :span="24">
          <el-card class="box-card" shadow="never">
            <div
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
              "
            >
              <div class="card-title">入库趋势</div>
              <el-radio-group v-model="tabPositionIn" @change="dateChangeIn">
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="year">今年</el-radio-button>
              </el-radio-group>
            </div>
            <div
              style="height: calc(100% - 30px)"
              v-if="barChartDataIn.xData.length"
            >
              <StationBar
                height="100%"
                :chartData="barChartDataIn"
                :xName="barXName"
                :setting="{
                  seriesName: '入库数量',
                  yName: '吨',
                }"
              />
            </div>
          </el-card>
        </el-col>
        <el-col :span="24">
          <el-card class="box-card" shadow="never">
            <div
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
              "
            >
              <div class="card-title">出库趋势</div>
              <el-radio-group v-model="tabPositionOut" @change="dateChangeOut">
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="year">今年</el-radio-button>
              </el-radio-group>
            </div>
            <div
              style="height: calc(100% - 30px)"
              v-if="barChartDataOut.xData.length"
            >
              <StationBar
                height="100%"
                :chartData="barChartDataOut"
                :xName="barXName"
                :setting="{
                  seriesName: '出库数量',
                  yName: '吨',
                }"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <!-- <div class="station-bottom">
      <el-row :gutter="12">
        <el-col :span="6">
          <el-card class="box-card" shadow="never">
            <div class="card-title">近7日销售出库</div>
            <div style="height: calc(100% - 30px);">
              <StationLine height="100%" itemColor="#ee4368" yName="件" :chartData="lineDataOne"/>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="box-card" shadow="never">
            <div class="card-title">近7日领料出库</div>
            <div style="height: calc(100% - 30px);">
              <StationLine height="100%" :chartData="lineDataTwo" yName="件" itemColor="#5470c6"/>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="box-card" shadow="never">
            <div class="card-title">近7日移库</div>
            <div style="height: calc(100% - 30px);">
              <StationLine height="100%"  :chartData="lineDataThree" yName="件"
                           itemColor="#c58bea"
              />
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="box-card" shadow="never">
            <div class="card-title">近7日退货入库</div>
            <div style="height: calc(100% - 30px);">
              <StationLine height="100%" yName="件" :chartData="lineDataFour"
                           itemColor="#c7a428"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div> -->
  </div>
</template>
<script setup>
import { trend, summary, productionSummary, queryWeightDetails } from "@/api/wms/shouye";
import StationPie from "./components/StationPie.vue";
import StationLine from "./components/StationLine.vue";
import StationBar from "./components/StationBar.vue";
import { ElMessageBox, ElMessage } from "element-plus";
import dayjs from "dayjs";
import { onMounted, ref } from "vue";
import moment from "moment";
let intervalId;

const tabPositionIn = ref("month");
const tabPositionOut = ref("month");
const barChartDataIn = ref({
  yData: [],
  xData: [],
});
const barChartDataOut = ref({
  yData: [],
  xData: [],
});
const barXName = ref("日");
const lineDataOne = ref({
  yData: [],
});
const lineDataTwo = ref({
  yData: [],
});
const lineDataThree = ref({
  yData: [],
});
const lineDataFour = ref({
  yData: [],
});
const statisticIn = ref({});
const statisticOut = ref({});
const staObj = ref({});
const topLL = ref({});

onMounted(() => {
  dateChangeIn("month");
  dateChangeOut("month");
  getSummary();
  getAllNeed();
  // 开始轮询 getAllNeed，每 20 秒一次
  intervalId = window.setInterval(() => {
    getAllNeed();
  }, 20000); // 20000 毫秒 = 20 秒
});

onBeforeUnmount(() => {
  // 清除轮询，防止内存泄漏
  if (intervalId) {
    clearInterval(intervalId);
  }
});

function getAllNeed() {
  getTopDetails();
  getAllAmount();
}

// 时间类型选择(入库)
function dateChangeIn(value) {
  console.log(value, "value");
  let params = {
    stockType: "stockIn",
  };
  if (value == "year") {
    params.year = dayjs().format("YYYY");
  } else {
    params.year = dayjs().format("YYYY");
    params.month = dayjs().format("MM");
  }
  console.log(params, "params");
  trend(params)
    .then((pre) => {
      barChartDataIn.value.xData = pre.data.map((pre) => pre.dataTime);
      barChartDataIn.value.yData = pre.data.map((pre) => pre.total/1000);
    })
    .catch(() => {
      ElMessage.error("获取数据失败");
    });
  // let date = new Date()
  // let month = date.getMonth() + 1
  // let day = date.getDate()
  // let barXData = []
  // let barYData = []
  // if(value === 'year') {
  //   for(let i = 0; i < month; i++) {
  //     barXData.push(moment().subtract(i, 'months').format('YYYY-MM'))
  //     barYData.push(Math.floor(Math.random()*(180-120+1))+120)
  //   }
  //   barXName.value = '月'
  // } else {
  //   for(let i = 0; i < day; i++) {
  //     barXData.push(moment().subtract(i, 'days').format('MM-DD'))
  //     barYData.push(Math.floor(Math.random()*(30-15+1))+15)
  //   }
  //   barXName.value = '日'
  // }
  // barChartData.value = {
  //   xData: barXData.reverse(),
  //   yData: barYData
  // }
}
// 时间类型选择(出库)
function dateChangeOut(value) {
  console.log(value, "value");
  let params = {
    stockType: "stockOut",
  };
  if (value == "year") {
    params.year = dayjs().format("YYYY");
  } else {
    params.year = dayjs().format("YYYY");
    params.month = dayjs().format("MM");
  }
  console.log(params, "params");
  trend(params)
    .then((pre) => {
      barChartDataOut.value.xData = pre.data.map((pre) => pre.dataTime);
      barChartDataOut.value.yData = pre.data.map((pre) => pre.total/1000);
    })
    .catch(() => {
      ElMessage.error("获取数据失败");
    });
  // let date = new Date()
  // let month = date.getMonth() + 1
  // let day = date.getDate()
  // let barXData = []
  // let barYData = []
  // if(value === 'year') {
  //   for(let i = 0; i < month; i++) {
  //     barXData.push(moment().subtract(i, 'months').format('YYYY-MM'))
  //     barYData.push(Math.floor(Math.random()*(180-120+1))+120)
  //   }
  //   barXName.value = '月'
  // } else {
  //   for(let i = 0; i < day; i++) {
  //     barXData.push(moment().subtract(i, 'days').format('MM-DD'))
  //     barYData.push(Math.floor(Math.random()*(30-15+1))+15)
  //   }
  //   barXName.value = '日'
  // }
  // barChartData.value = {
  //   xData: barXData.reverse(),
  //   yData: barYData
  // }
}
function getSummary() {
  const params = {
    recentDays: 7,
  };
  summary(params)
    .then((res) => {
      console.log(res, "res");
      res.data.forEach(pre=>{
        pre.total = (+pre.total).toFixed(2)
      })
      const inObj = {
        today: (res.data.find(
          (pre) => pre.stockType == "stockIn" && pre.dataTime == "today"
        )?.total/1000).toFixed(3),
        yesterday: (res.data.find(
          (pre) => pre.stockType == "stockIn" && pre.dataTime == "yesterday"
        )?.total/1000).toFixed(3),
        recent: (res.data.find(
          (pre) => pre.stockType == "stockIn" && pre.dataTime == "recent"
        )?.total/1000).toFixed(3),
      };
      statisticIn.value = inObj;
      const outObj = {
        today: (res.data.find(
          (pre) => pre.stockType == "stockOut" && pre.dataTime == "today"
        )?.total/1000).toFixed(3),
        yesterday: (res.data.find(
          (pre) => pre.stockType == "stockOut" && pre.dataTime == "yesterday"
        )?.total/1000).toFixed(3),
        recent: (res.data.find(
          (pre) => pre.stockType == "stockOut" && pre.dataTime == "recent"
        )?.total/1000).toFixed(3),
      };
      statisticOut.value = outObj;
    })
    .catch(() => {
      ElMessage.error("获取数据失败");
    });
}
function getAllAmount() {
  productionSummary()
    .then((res) => {
      console.log(res, "res");
      staObj.value = {
        stockIn: (res.data.find((pre) => pre.stockType == "stockIn")?.total/1000).toFixed(2),
        stockOut: (res.data.find((pre) => pre.stockType == "stockOut")?.total/1000).toFixed(2),
        infeed: res.data.find((pre) => pre.stockType == "infeed")?.total,
      };
    })
    .catch(() => {
      ElMessage.error("获取数据失败");
    });
}
function getTopDetails() {
  queryWeightDetails()
    .then((res) => {
      res.data.forEach(pre=>{
        if(pre.weightType == 'ht1') {
          topLL.value.weight1 = pre.weight/1000;
          topLL.value.time1 = pre.weightTime;
        } else if (pre.weightType == 'ht2') {
          topLL.value.weight2 = pre.weight/1000;
          topLL.value.time2 = pre.weightTime;
        } else {
          topLL.value.weight3 = pre.weight/1000;
          topLL.value.time3 = pre.weightTime;
        }
      })
    })
    .catch(() => {
      ElMessage.error("获取数据失败");
    });
}
// 初始化时间模拟数据
function initTime() {
  let lineXData = [];
  for (let i = 0; i < 7; i++) {
    lineXData.push(moment().subtract(i, "days").format("MM-DD"));
  }
  lineXData = lineXData.reverse();
  lineDataOne.value.xData = lineXData;
  lineDataTwo.value.xData = lineXData;
  lineDataThree.value.xData = lineXData;
  lineDataFour.value.xData = lineXData;
}
</script>

<style scoped>
.app-container {
  min-height: calc(100vh - 84px);
  padding: 12px 12px 0 12px;
}

.top-item-box {
  height: 160px;
  background: #fff;
  margin-bottom: 12px;
  border-radius: 12px;
  color: #fff;
  padding: 16px;
}

.item-box-one {
  background: linear-gradient(30deg, #1a94db, #4db1eb, #7acaf9);
  box-shadow: 0 4px 12px #8ed2fa;
}

.item-box-two {
  background: linear-gradient(30deg, #c7a327, #d5ba47, #e3cf65);
  box-shadow: 0 4px 12px #ece7cd;
}

.item-box-three {
  background: linear-gradient(30deg, #6365f7, #9177f1, #cd8ee9);
  box-shadow: 0 4px 12px #dcc9e6;
}

.item-box-four {
  background: linear-gradient(30deg, #ed3a60, #f1557a, #f67da0);
  box-shadow: 0 4px 12px #e7cfd6;
}

.box-card {
  height: 400px;
  margin-bottom: 12px;
  background-color: #fff;
  border-color: #ebe6f5;
}

.box-card >>> .el-card__body {
  height: 100%;
}

.card-title {
  font-weight: bold;
  height: 30px;
  display: flex;
  align-items: center;
}

.card-title::before {
  content: "";
  height: 70%;
  width: 5px;
  background: #3671e8;
  margin-right: 8px;
}
</style>
